<template>
  <div>
    <div class="example" v-if="cardLoading">
      <a-spin />
    </div>
    <a-tree
      v-else
      class="draggable-tree"
      :draggable="draggable"
      :tree-data="categoryTreeList"
      :defaultExpandAll="false"
      :defaultExpandedKeys="defaultExpandedKeys"
      @select="selectNode"
    >
    </a-tree>
  </div>
</template>

<script>
import { getAction } from '@api/manage'

export default {
  created() {
    this.initCategoryTree()
  },
  data() {
    return {
      categoryTreeList: [],
      draggable: false,
      cardLoading: false,
      defaultExpandedKeys: [],
      chooseExpandedKeys: [],
      selectNodeId: '',
      url:
        {
          getCategoryTree: '/product/category/getCategoryTree'
        }
    }
  },
  methods: {
    /**
     * 初始化分类树 数据
     */
    initCategoryTree() {
      this.cardLoading = true
      getAction(this.url.getCategoryTree).then(res => {
        if (res.success) {
          this.categoryTreeList = res.result
          this.addDisabledForNodesWithChildren(this.categoryTreeList)
        } else {
          this.$message.error(res.message)
        }
      }).finally(() => {
        this.cardLoading = false
      })
    },
    /**
     * 选择节点
     * @param node
     */
    selectNode(node) {
      let nodeId = node[0]
      if (nodeId !== undefined) {
        this.selectNodeId = nodeId
      }
      this.$emit('node', this.selectNodeId)
    },
    addDisabledForNodesWithChildren(nodes) {
      nodes.forEach(node => {
        if (node.children && node.children.length > 0) {
          node.selectable = false
          this.addDisabledForNodesWithChildren(node.children)
        }
      })
    }
  }
}
</script>
<style scoped>
.example {
  text-align: center;
  border-radius: 4px;
  margin-bottom: 20px;
  padding: 30px 50px;
  margin: 20px 0;
}
</style>
